from pymongo import MongoClient
from common.utils.config_util import EnvConfig


class MongoDBUtil:
    def __init__(self, db_name, config={}):
        # 不传mongo配置，则读取配置文件的配置
        if not config:
            env_config = EnvConfig.get_config()
            mongo_config = env_config['mongo']
            config = mongo_config

        username = config.get('username')
        password = config.get('password')
        host = config.get('host')
        port = config.get('port', 27017)
        if not host:
            raise ValueError('host不能为空!')
        if username and password:
            self.client = MongoClient(f"mongodb://{username}:{password}@{host}:{port}/{db_name}")
        else:
            self.client = MongoClient(host, port)
        self.db = self.client[db_name]

    def insert_one(self, collection_name, insert_data):
        collection = self.db[collection_name]
        result = collection.insert_one(insert_data)
        return result.inserted_id

    def insert_many(self, collection_name, insert_data):
        if not isinstance(insert_data, list):
            raise TypeError('类型必须为list!')
        collection = self.db[collection_name]
        result = collection.insert_many(insert_data)
        return result.inserted_ids

    def find_one(self, collection_name, query={}):
        collection = self.db[collection_name]
        result = collection.find_one(query)
        return result

    def find(self, collection_name, query={}):
        collection = self.db[collection_name]
        cursor = collection.find(query)
        result = list(cursor)
        return result

    def update_one(self, collection_name, query, update_data):
        collection = self.db[collection_name]
        result = collection.update_one(query, {"$set": update_data})
        return result.modified_count

    def update_many(self, collection_name, query, update_data):
        collection = self.db[collection_name]
        result = collection.update_many(query, {"$set": update_data})
        return result.modified_count

    def delete_one(self, collection_name, query):
        collection = self.db[collection_name]
        result = collection.delete_one(query)
        return result.deleted_count

    def delete_many(self, collection_name, query):
        collection = self.db[collection_name]
        result = collection.delete_many(query)
        return result.deleted_count


if __name__ == '__main__':
    db = MongoDBUtil('test', {'host': 'localhost'})
    data = {'username': 'xiaoming'}
    # db.insert_one('case', data)
    results = db.find('case')
    print(results)
    # print(db.update_one('case', {'username': 'xiaohong'}, {'age': 18}))
    # # print(db.insert_many('case', [{'username': 'xiaozhang'}, {'username': 'xiaoli'}]))
    # print(db.update_many('case', {'username': 'xiaoming'}, {'age': 22}))
    # print(db.delete_many('case', {'username': 'xiaoming'}))
